package com.garlic.face.jlf;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.alipay.iotlab.eyasoundsdk.SoundManager;
import com.alipay.iotlab.eyasoundsdk.soundbank.SoundManagerInitCallback;
import com.alipay.iotlab.eyasoundsdk.util.ILogger;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.balance.MySQLiteOpenHelper;
import com.garlic.face.jlf.transaction.balance.greendao.gen.DaoMaster;
import com.garlic.face.jlf.transaction.balance.greendao.gen.DaoSession;
import com.garlic.face.jlf.utils.LogUtils;
import com.garlic.face.jlf.utils.ProccessChecker;
import com.garlic.face.jlf.utils.Tools;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortFinder;

public class App extends Application {

    private SerialPortFinder serialPortFinder=new SerialPortFinder();

	//这儿需要修改为您自己的包名
	private static final String MAIN_PROCESS_NAME = "com.garlic.face.jlf";

    private static DbManager.DaoConfig mDaoConfig;

    private static Context mContext = null;

    private static boolean isDebug = false;

    //这里三个值请填写自己真实的值
    //应用的签名私钥
    private final static String appKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL2Px6+3EPoXnQiI\n" +
            "1Ktqkn2lmyuczpf4l3vc0Fu96Z9KTiAWJFE2sokiM7RaVB/J2E6m2t8jQe0sO9wW\n" +
            "4pZeVkykBdpF3tX22KaCXzvaYohf3lohV3PBvqB21UAgcCIjpgi3rqVGB0GUuG/Y\n" +
            "I+nYWLfQN/ZsHz6K40cTM+OQrzq9AgMBAAECgYAiD7PR3xMt3RBaeDu+kWfBLAC1\n" +
            "1XdJ12Fg4EyQL4/LD476NQBRl4J9IagowBJdo+c6OsEZVzyBYXFgGrycSFc5Hppt\n" +
            "GoULkNrOMcO1pqx8vc/1Odt5uUAC1Yu9Ea1pEIE/vY8lcR3J+ZSh3c+fcm3lzs7u\n" +
            "BZQVc0N0EoE6c9hAAQJBAPXppoAuh/Aq8ja3M+B3E0Tj3crpPNJe8cJtVfBfP3Jh\n" +
            "pE58zmotjLaN4MFNecv6WmSIn1v0C/GLET45K+/QMcUCQQDFVmHs8kJraNr6kk4C\n" +
            "6rADDNq7ofZ8CB2KWZjaRd6QWOicWW0dK+ZyXtTy+qvUbSRy4uMjmeoXaXEuQWRj\n" +
            "P0yZAkEA3oCUmHKBqTsSgZNuKvFSzAhpTAmRcL9bfBI1qhJkc/gJFMM0eTnRkfP5\n" +
            "oq2ZQIi7dS9xEWBV1i2AYo6URJ5aCQJAVuyKDhlYcH+rlZxEiLxf87gB0YyySkg4\n" +
            "2uxEjEEinGrNa7FoguUHiXGEU9NfRR8eYwzWCKSPnOhxVnKviZgkYQJBALW0+x37\n" +
            "e6cONJiKtZSj1WzLmUtafRTPTJ+LmvZhtqLGRkE22qWpTVQ3eijNoKHAfDF3FZCA\n" +
            "H+Y/ECxbZxj3oJA=";
    //商户id
    private final static String partnerId = "2088911212092405";
    //应用的appId
    private final static String appId = "2016030701192937";


    //超过200000万则不支持刷脸
    public static final int NO_SUPPORT_FACE_PAY = 2000;

    //一系列需要存储到sp的数据
    public static final String CONFIG_INFO = "config_info";
    public static final String SHOP_NO = "shop_no";
    public static final String SHOP_NAME = "shop_name";
    public static final String POS_NO = "pos_no";
    public static final String POS_IP = "pos_ip";
    public static final String POS_PORT = "pos_port";
    public static final String CASH_NAME = "cashier_name";
    public static final String CASH_PWD = "cashier_pwd";
    public static final String DEVICE_NUM = "device_num";
    public static final String NEED_INSERT_SQL = "need_insert_sql";
	public static final String NEED_CLOSE_WEIGTH = "need_close_weigth";
    public static final String LANGUAGE_KEY = "LANGUAGE";

	//静态单例
	public static App instances;
	private static MySQLiteOpenHelper mHelper;
	private SQLiteDatabase db;
	private DaoMaster mDaoMaster;
	private DaoSession mDaoSession;
	private static SoundManager soundMgr;

	@Override
	public void onCreate() {
		super.onCreate();
		//因为管控SDK会导致Application的onCreate多次调用
		if (ProccessChecker.isAppMainProcess(this, MAIN_PROCESS_NAME)) {
			mContext = this;
			//CrashHandler crashHandler = CrashHandler.getInstance();
			//crashHandler.init(this);
			//所有初始化代码放在这里
			x.Ext.init(this);
			x.Ext.setDebug(true);
			loadInfoToMemory();
			instances = this;
			initSqlLite();
			//CrashReport.initCrashReport(getApplicationContext(), "50ab8317d1", false);
			init();
			initSound();
		}


    }

	private void initSound() {
		soundMgr = SoundManager.getInstance();
		soundMgr.release();
		soundMgr.init(getInstances(), new SoundManagerInitCallback() {
			@Override
			public void initFinished(int i) {
				LogUtils.d("语音包初始化完毕", false);
			}
		});
		soundMgr.setLogger(logger);
	}

	public static SoundManager getSoundMgr(){
		return soundMgr;
	}

	public static void playSound(String eventId){
		if(!Tools.getLanguage().equals(Locale.US.toString())) {
			soundMgr.play(eventId);
		}
	}

	ILogger logger = new ILogger() {
		@Override
		public void v(String tag, String msg) {
			LogUtils.v(tag + "*_*_*" + msg, false);
		}

		@Override
		public void d(String tag, String msg) {
			LogUtils.d(tag + "*_*_*" + msg, false);
		}

		@Override
		public void i(String tag, String msg) {
			LogUtils.i(tag + "*_*_*" + msg, false);
		}

		@Override
		public void w(String tag, String msg) {
			LogUtils.w(tag + "*_*_*" + msg, false);
		}

		@Override
		public void e(String tag, String msg) {
			LogUtils.e(tag + "*_*_*" + msg);
		}
	};

    private void init() {
        String language = Tools.getLanguage();
        if (language != null) {
            switch (language) {
                case "zh_CN":
                    updateLocale(Locale.SIMPLIFIED_CHINESE);
                    break;
                case "en_US":
                    updateLocale(Locale.US);
                    break;
            }
        }
    }

    public static App getInstances(){
        return instances;
    }

    public static MySQLiteOpenHelper getSQLiteOpenHelper(){
        return mHelper;
    }

    private void loadInfoToMemory() {
        Tools.copyShopInfoToMemory();
    }

    public static Context getContext() {
        return mContext;
    }

    public static boolean isDebug() {
        return isDebug;
    }

    private void initSqlLite() {
        // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        mHelper = new MySQLiteOpenHelper(this, "cclcloud", null);
        db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public static String getFaceSrvPrefixUrl() {
//        return "http://192.168.64.240:40034/";
        return "http://facepay.guangfen.net/";
    }

    public static String getPayPrefixUrl() {
//        return "http://192.168.64.240:18080/";
        return "http://www.miaofutech.com/";
    }

    private static final String FACE_PAY_FILE = "face_pay";


    public static String getFakeBarCode() {
        int min = 1;
        int max = 400;
        Random random = new Random();
        int num = random.nextInt(max) % (max - min + 1) + min;
        return num + "";
    }

	private static List<BaseActivity> mActivityStack = new ArrayList<>();
	private static List<BaseActivity> mExitActivityStack = new ArrayList<>();


	public static void addActivity(BaseActivity activity) {
		String className = activity.getClass().getSimpleName();
		mExitActivityStack.add(activity);
		if (!className.equals("MainActivity") && !className.equals("SplashActivity")) {
			mActivityStack.add(activity);
		}
		LogUtils.d("mActivityStack 数量" + mActivityStack.size(), false);
	}

	public static boolean isMainActivity(){
		if(mExitActivityStack.size()>0){
			if(mExitActivityStack.get(mExitActivityStack.size()-1).getClass().getSimpleName().equals("MainActivity")){
				return true;
			}
		}
		return false;
	}

	public static void removeActivity(BaseActivity activity) {
		if (mActivityStack.contains(activity)) {
			mActivityStack.remove(activity);
			mExitActivityStack.remove(activity);
		}
	}

	public static void exitApp() {
		for (int i = 0; i < mExitActivityStack.size(); i++) {
			BaseActivity a = mExitActivityStack.get(i);
			if (a != null && !a.isFinishing()) {
				a.finish();
			}
		}
		mExitActivityStack.clear();
	}

	public static void clearToMainActivity() {
		//从当前界面删除
		for (int i = 0; i < mActivityStack.size(); i++) {
			BaseActivity a = mActivityStack.get(i);
			if (a != null && !a.isFinishing()) {
				mExitActivityStack.remove(a);
				a.finish();
			}
		}
		mActivityStack.clear();
	}

	public static String getAppKey() {
		return appKey;
	}

	public static String getPartnerId() {
		return partnerId;
	}

	public static String getAppId() {
		return appId;
	}

	public static List<BaseActivity> getActivityStack() {
		return mActivityStack;
	}

	public SerialPortFinder getSerialPortFinder() {
		return serialPortFinder;
	}

	private SerialPort mSerialPort = null;

	public SerialPort getSerialPort(String devicesName) throws SecurityException, IOException, InvalidParameterException, InterruptedException {
		if (mSerialPort == null) {
			/* Read serial port parameters */
			String path = "";
			int baudrate = -1;
			String preferenceName = this.getPackageName() + "_preferences";
			if (devicesName.equals("scale")) {
				//电子称的
				SharedPreferences sp = getSharedPreferences(preferenceName, MODE_PRIVATE);
				path = sp.getString("DEVICE", "");
				baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
			} else if (devicesName.equals("light")) {
				//灯的
				SharedPreferences sp = getSharedPreferences(preferenceName, MODE_PRIVATE);
				path = sp.getString("DEVICE", "");
				baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
			}

            /* Check parameters */
			if ((path.length() == 0) || (baudrate == -1)) {
				throw new InvalidParameterException();
			}

            /* Open the serial port */
			Process su;
			su = Runtime.getRuntime().exec("/system/xbin/su");
			String cmd = "chmod 777 " + path + "\n"
					+ "exit\n";
				/*String cmd = "chmod 777 /dev/s3c_serial0" + "\n"
				+ "exit\n";*/
			su.getOutputStream().write(cmd.getBytes());
			if ((su.waitFor() != 0)) {
				throw new SecurityException();
			}
			System.out.println(">>>>>>>>>" + path + "  " + baudrate);
			mSerialPort = new SerialPort(new File(path), baudrate, 0);
		}
		return mSerialPort;
	}

	public void updateLocale(Locale locale) {
		if (locale == null) {
			locale = Locale.getDefault();
		}

		Resources resources = getResources();
		Configuration config = resources.getConfiguration();
		config.locale = locale;
		resources.updateConfiguration(config, resources.getDisplayMetrics());
	}


    public void saveLanguage(String language) {
        if (TextUtils.isEmpty(language)) {
            return;
        }
        Tools.setLanguage(language);
    }

    /*
    public static boolean verifyCountGoods(String barcode){
		boolean result = false;
		String code = barcode.replaceAll("^[a-zA-Z]", "");
		if((code.length() == 18) || (code.length() == 24)){
			String shortCode = code.substring(6, 12);
			Log.e("short Code", shortCode);
			if((Integer.valueOf(shortCode)%1000) == 0){
				result = true;
			}
		}
		return result;

	}
	*/
}
